import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isRelogin } from '@/utils/request'
import { checkCoursePermissionApi } from "@/api/system/user";
import VueRouter from 'vue-router'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  let redirectedFrom = to.redirectedFrom ? to.redirectedFrom : null
  NProgress.start()
  // if (to.path.includes("web-apps/apps")) {
  //   next();
  //   NProgress.done();
  // } else {
  if (getToken()) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      let courseId = to.query.courseId;
      let path = to.path;
      //鉴权
      if (store.getters.curRole=='teacher' && courseId && !path.includes("recommendCourseDetial") ){
        let params = {
          courseId: courseId,
          teacherId:store.getters.teacherId
        }
        checkCoursePermissionApi(params).then((res)=>{
          if (res.data){
            next()
          }else {
            next({path:'/401',query:{type:'checkCoursePermission'}})
          }
        })
        return
      }
      if (store.getters.roles.length === 0) {
        isRelogin.show = true
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => {
          isRelogin.show = false
          let arr = [
            {
              label: '工作站',
              key: 'workstationName',
              newName: '工作站',
              path: '/workstation'
            },
            {
              label: '课程',
              key: 'courseName',
              newName: '课程',
              path: '/course'
            },
            {
              label: '任务',
              key: 'chapterName',
              newName: '任务',
              path: '/chapterName'
            },
            {
              label: '学校',
              key: 'schoolName',
              newName: '学校',
              path: '/schoolOrganization'
            },
            {
              label: '分院',
              key: 'branchName',
              newName: '分院',
              path: '/branchName'
            },
            {
              label: '专业',
              key: 'majorName',
              newName: '专业',
              path: '/majorName'
            },
            {
              label: '班级',
              key: 'gradeName',
              newName: '班级',
              path: '/gradeName'
            },
            {
              label: '课时量',
              key: 'hourAmount',
              newName: '基准学时',
              path: '/hourAmount'
            },
            {
              label: '步骤',
              key: 'procedure',
              newName: '步骤',
              path: '/procedure'
            },
            {
              label: '推荐学时',
              key: 'hourRecommended',
              newName: '任务学时',
              path: '/hourRecommended'
            }
          ]
          store.dispatch('GenerateRoutes', arr).then((accessRoutes) => {
            // 根据roles权限生成可访问的路由表
            router.matcher = new VueRouter().matcher
            router.addRoutes(accessRoutes) // 动态添加可访问路由表
            if (redirectedFrom) {
              next({ path: redirectedFrom })
            } else {
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
            }
          })
        }).catch((err) => {
          store.dispatch('LogOut').then(() => {
            Message.error({ message: err, showClose: true })
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
  // }
})

router.afterEach(() => {
  NProgress.done()
})
